import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormControl, FormGroup} from "@angular/forms";
import {Http} from "@angular/http";
import {ActivatedRoute} from "@angular/router";
import {MaintenanceService} from "../../shared/service/maintenance.service";
import {Maintenance} from "../../shared/model/maintenance";

@Component({
  selector: 'app-new-maintenance-type',
  templateUrl: './new-maintenance-type.component.html',
  styleUrls: ['./new-maintenance-type.component.css']
})
export class NewMaintenanceTypeComponent implements OnInit {


  userId: string = this.routeInfo.snapshot.queryParams['userId'];
  typeForm: FormGroup;
  IDValidFlag:boolean = false;
  statusFlag:boolean = false;
  public searchParam: FormControl = new FormControl();

  //选择车辆类型分页
  _dataSet = [];
  _current = 1;
  _pageSize = 10;
  _total = 1;

  //存储table中全部数据
  vehicleTypeData = [];

  _displayData: Array<any> = [];
  selected: any=[];

  //新增修改删除是否禁用标志
  btnDisabled:boolean = false;

  constructor(private fb: FormBuilder,
              private http: Http,
              private routeInfo: ActivatedRoute,
              private maintenanceService:MaintenanceService) { }

  ngOnInit() {

    this.typeForm = this.fb.group({
      oid: '',id: '', name: '', description: ''
    });

    this.getDatas();

  }

  //刷新数据
  refreshData(reset = false) {
    if (reset) {
      this._current = 1;
    }
    // this.getDatas();
  };


  //获取数据
  getDatas(){
    this.maintenanceService.getMaintenanceTypes().then(
      res => {
        this._dataSet = res;
        this.vehicleTypeData = res;
      }
    );
  }

  //车辆表格
  vehicleDisplayDataChange($event) {
    this._displayData = $event;
  };

  onSelect(data){

    this.selected = data;

    this.typeForm.reset({
      oid: data.oid,
      id: data.id,
      name: data.name,
      description: data.description
    });

    this.statusFlag = true;
    this.btnDisabled = true;
  }

  updateInfo(val:any){
    let msg ="";
    if(!this.typeForm.get("id").value.replace(/^\s+|\s+$/g,"")){
      msg +=("请输入类型代号\n");
    }
    if(!this.typeForm.get("name").value.replace(/^\s+|\s+$/g,"")){
      msg +=("请输入类型名称\n");
    }
    if(msg){
      alert(msg);
    }else{
      this.maintenanceService.updateMaintenanceType(this.typeForm.value).then(res => {
        //状态码1为成功
        if (res.code === 1) {
          alert(res.message);
          this.typeForm.reset({
            oid: '',
            id: '',
            name: '',
            description: ''
          });

          this.statusFlag = false;
          this.selected = [];
          this.getDatas();
          this.refreshData(true);
          this.clearParam();
          this.btnDisabled = false;
        } else {
          alert(res.message);
        }
      })
    }
  }

  onSubmit(val:any){
    if(!this.IDValidFlag&&this.typeForm.get("id").value){
      return false;
    }else if(this.statusFlag){
      alert("请点击修改按钮");
      return false;
    }else {
      let msg ="";
      if(!this.typeForm.get("id").value.replace(/^\s+|\s+$/g,"")){
        msg +=("请输入类型代号\n");
      }
      if(!this.typeForm.get("name").value.replace(/^\s+|\s+$/g,"")){
        msg +=("请输入类型名称\n");
      }

      if(msg){
        alert(msg);
      }else{
        this.maintenanceService.createMaintenanceType(this.typeForm.value).then(res => {
          //状态码1为成功
          if(res.code ===1){
            alert(res.message);
            this.typeForm.reset({
              oid: '',id: '', name: '', description: ''
            });
            this.getDatas();
            this.refreshData(true);
            this.clearParam();
          }else{
            alert(res.message);
          }
        })
      }
    }

  }

  //判断是否有重复ID
  toSearchId(){
    if(!this.statusFlag){
      let pid = this.typeForm.get('id').value;
      this.maintenanceService.checkMaintenanceTypeId(pid)
        .then(res => {
          console.log(res);
          if(res.code===1){
            alert("类型代号已存在，请重新输入！");
            this.typeForm.patchValue({
              id:'',
            });
            this.IDValidFlag = false;
          }else{
            this.IDValidFlag = true;
          }
        });
    }

  }

  //查询
  searchInfo(){
    let result = this.vehicleTypeData;
    result = result.filter((f: Maintenance) => f.name.indexOf(this.searchParam.value) !== -1);
    this._dataSet = result;
  }

  //删除
  delType():void {
    if(this.selected.oid != "" && this.selected.oid != undefined){
      if(confirm("确认删除?")){
        this.maintenanceService.deleteMaintenanceType(this.selected.oid).then(
          res => {
            if(res.code > 0){
              this.typeForm.reset({
                oid: '',id: '', name: '', description: ''
              });
              this.statusFlag = false;
              alert(res.message);
              this.getDatas();
              this.refreshData(true);
              this.clearParam();
              this.btnDisabled = false;
            }
          }
        )
      }
    }else{
      alert("请选择一条要删除的数据！\n");
    }

  }

  //清空表格
  clear(){
    this.typeForm.reset({
      oid: '',id: '', name: '', description: ''
    });
    this.selected = [];
    this.statusFlag = false;
    this.btnDisabled = false;
  }

  //清空查询条件
  clearParam(){
    $("#searchpa").val("");
    this.searchParam.reset("");
  }

}
